/*******************************************************************************
 * Copyright (c) 2008-2009 zhang yuexiang.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package org.xfeep.asura.bootstrap;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import org.xfeep.asura.core.ComponentDefinition;
import org.xfeep.asura.core.ComponentManager;
import org.xfeep.asura.core.logger.CoreLoggerManager;

public class AllPackageBundleInClassPathComponentLoader implements
		ComponentLoader {

	public AllPackageBundleInClassPathComponentLoader() {
	}
	
	public List<ComponentDefinition> getStaticLoadComponents(ClassLoader classLoader) throws IOException {
		List<File> libraryFiles = new ArrayList<File>();
		ClassLoader loader = classLoader;
		while (loader != null){
			if (loader instanceof URLClassLoader) {
				URLClassLoader urlClassLoader = (URLClassLoader) loader;
				for (URL url : urlClassLoader.getURLs()){
					try {
						File f = new File(url.toURI());
						libraryFiles.add(f);
					} catch (URISyntaxException e) {
						CoreLoggerManager.getDefaultLogger().warn("parse library file fail, the url is " + url , e);
					}
				}
			}
			loader = loader.getParent();
		}
		PackageBundleComponentLoader[] clds = new PackageBundleComponentLoader[libraryFiles.size()];
		for (int i = 0; i < clds.length; i++){
			clds[i] = new PackageBundleComponentLoader(libraryFiles.get(i));
		}
		List<ComponentDefinition> rt = new ArrayList<ComponentDefinition>();
		for (PackageBundleComponentLoader pl : clds){
			rt.addAll(pl.getStaticLoadComponents(classLoader));
		}
		return rt;
	}

	public void initialize(ComponentManager componentManager) {

	}

	public void setupComponentDynamicLoadListener(
			ComponentDynamicLoadListener listener) {
	}

}
